import axios from 'axios'
import { MessageBox, Message } from 'element-ui'

const server = axios.create({
  // baseURL: 'http://127.0.0.1:8888/api/private/v1',
  baseURL:"https://lianghj.top:8888/api/private/v1/",
  timeout: 5000
})

//请求拦截
server.interceptors.request.use(config => {
  let token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, error => {
  Promise.reject(error)
})

//响应拦截
server.interceptors.response.use(res => {

  console.log('响应成功数据', res);

  let code = res.data.meta.status //响应状态码

  if (res.data.meta.msg == "无效token") {

    MessageBox.confirm('token过期, 是否跳转到登录页面?', '提示', {
      confirmButtonText: '重新登录',
      cancelButtonText: '取消',
      type: 'warning'
      
    }).then(() => {
      location.href = '/login'

    }).catch(() => {

    })
  }

  if (code === 400 || code === 401 || code === 403 || code === 404 || code === 500) {
    Message.error({
      duration: 1000,
      message: res.data.meta.msg
    })
  }
  return res.data

}, error => {
  console.log('响应错误', error);

  let { message } = error;

  if (message == "Network Error") {
    message = "后端接口连接异常";
  }
  else if (message.includes("timeout")) {
    message = "系统接口请求超时";
  }

  Message({
    message: message,
    type: 'error',
    duration: 1000
  })

  Promise.reject(error)
})
export default server